@/*
按钮标签中各个参数的说明:
path:上传的id
accept: 文件类型 可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
multiple: 多文件(true/false)
readonly: 只读true
onlyTag : 是否只显示标签
@*/
@var accept = accept!'file';
@var id = tag.format(path);
@var name = path;
@var multiple = multiple!'false';

<div class="layui-upload">
    @if(isNotEmpty(label)){
    <label for="${id}">${label!}</label>
    @}
    <input type="hidden" id="${id}" name="${name}" value="${value!}">
    <div id="${id}file" style="overflow: hidden"></div>
    <div style="overflow: hidden;margin-left: 10%;">
        @if(!fnc.isTrue(readonly!'false')){
        <button type="button" class="layui-btn layui-btn-normal" id="${id}Button">选择</button>
        <button type="button" class="layui-btn layui-btn-normal" id="${id}Clean">清除</button>
        @}
    </div>
</div>

<script>
    layui.use('upload', function () {
        var ${id}upload = layui.upload;
        ${id}upload.render({
            elem: '#${id}Button'
            , url: '/upload/file'
            , accept: '${accept}'
            , drag: false
            , multiple: ${multiple}
            , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                obj.preview(function(index, file, result){
                  if(file.size>0){
                      layer.load(); //上传loading
                  }else{
                     layer.msg("文件内容不能为空!");
                  }
                });

            }
            , done: function (res, index, upload) { //每个文件提交一次触发一次。详见“请求成功的回调”
                var fileName = res.fileName;
                var filePath = res.filePath;
                var fileType = res.fileType;
                updateFile${id}(fileName, fileType, filePath);
                layer.closeAll('loading'); //关闭loading
            }
            , allDone: function (obj) { //当文件全部被提交后，才触发
                // layer.msg(obj.successful + "个文件上传成功!");
                // console.log(obj.total); //得到总文件数
                // console.log(obj.successful); //请求成功的文件数
                // console.log(obj.aborted); //请求失败的文件数
            }
            , error: function (index, upload) {
                layer.closeAll('loading'); //关闭loading
            }
        });
    });

    //更新UI及值域
    function updateFile${id}(name, type, url) {
        if (!${multiple}) {
            $("#${id}Clean").click();
        }

        var value = $('#${id}').val();
        if ('${accept}' == 'images' || type == 'image') {
            $("#${id}file img[src*='" + name + "']").parent().remove();
            $('#${id}').val(getUrls${id}(value, url, name));
            $('#${id}file').append(createImage${id}(Feng.ctxPath + "/" + url, name));
            ${id}bindImgShow();
        } else {
            $("#${id}file div[myattr='" + url + "']").parent().remove();
            $('#${id}').val(getUrls${id}(value, url, name));
            $('#${id}file').append(createFile${id}(Feng.ctxPath + "/" + url, name));
        }
    }

    //更新值域值
    function getUrls${id}(value, url, name) {
        if (value.indexOf(name) > 0) {
            var urls = value.split("|");
            value = '';
            for (var i = 1; i < urls.length; i++) {
                if (urls[i].indexOf(name) > 0) {
                    urls[i] = url;
                }
                value = value + "|" + urls[i];
            }
        } else {
            value = value + "|" + url;
        }
        return value;
    }

    //创建图片预览
    function createImage${id}(url, name) {
        var $imgDiv = $("<div style='float: left;position: relative;padding: 10px'></div>");
        $imgDiv.append("<img src='" + url + "' style='width: 100px;height: 100px' title='" + name + "'>");
        $imgDiv.append("<a href='javascript:;' onclick='clean${id}(this)' style='color: #E64B3C;font-size: 18px;position: absolute;top: 0px;right: 0px;'><i class='fa fa-minus-circle'></i></a>");
        $imgDiv.append("<p style='width: 100px;;height: 20px;text-align: center;overflow: hidden;font-size: xx-small' title='" + name + "'>" + name + "</p>");
        return $imgDiv;
    }


    function ${id}View(urls) {
        var array = urls.split("|");
        for (var i = 1; i < array.length; i++) {
            var index = array[i].lastIndexOf("/");
            var name = array[i].substr(index + 1);
            var suffix = Feng.suffix(name);
            var doc = '';
            var url = Feng.ctxPath + "/" + array[i];
            if ('${accept}' == 'images' || suffix == 'jpg' || suffix == 'jpeg' || suffix == 'gif' || suffix == 'png') {
                doc = createImage${id}(url, name);
            } else {
                doc = createFile${id}(url, name, '${accept}')
            }
            $('#${id}file').append(doc);
        }
    }

    // //创建文件列表
    // function createFile(url, name) {
    //     var $imgDiv = $("<div></div>");
    //     $imgDiv.append("<a href='" + url + "'>" + name + "</a>");
    //     $imgDiv.append("<a href='javascript:;' onclick='clean(this)' style='color: blue'>x</a>");
    //     return $imgDiv;
    // }

    //创建文件预览
    function createFile${id}(url, name, type) {
        var className = '';
        if (type == 'video') {
            className = 'tpjl1';
        } else if (type == 'audio') {
            className = 'tpjl2';
        } else {
            var f_type = Feng.suffix(name);
            if (f_type == 'doc' || f_type == 'docx') {
                className = 'tpjl';
            } else if (f_type == 'ppt' || f_type == 'pptx') {
                className = 'tpjl3';
            } else if (f_type == 'xls' || f_type == 'xlsx') {
                className = 'tpjl4';
            } else if (f_type == 'pdf') {
                className = 'tpjl5';
            } else if (f_type == 'zip' || f_type == 'rar') {
                className = 'tpjl6';
            } else if (f_type == 'txt') {
                className = 'tpjl7';
            } else {
                className = 'tpjl8';
            }
        }
        var $imgDiv = $("<div style='float: left;position: relative;padding: 10px'></div>");
        var $mydiv = $("<div myattr='" + url + "' class='" + className + "'></div>");
        $mydiv.append("<a href='javascript:;' onclick='clean${id}(this)' style='color: #E64B3C;font-size: 18px;position: absolute;top: 0px;right: 0px;'><i class='fa fa-minus-circle'></i></a>");
        $imgDiv.append($mydiv);
        $imgDiv.append("<span style='width: 100px;display: block;text-align: center;' title='" + name + "'> <a style='text-decoration:none' href='" + url + "' download='' target='_blank'>" + name + "</a> </span>");
        return $imgDiv;
    }


    //清除
    function clean${id}(n) {
        var url = '';

        var img = $(n).parent().children("img").attr("src");
        if (img == undefined) {
            url = "|" + $(n).parent().attr("myattr").substring(1);
            $(n).parent().parent().remove();
        } else {
            url = "|" + img.substring(1);
            $(n).parent().remove();
        }
        var value = $('#${id}').val().replace(url, "");
        $('#${id}').val(value);


    }

    //全部清除
    $("#${id}Clean").click(function () {
        $('#${id}').val('');
        $('#${id}file').html('');
    });

    //初始化
    $(function () {
        var ${id}Value = $('#${id}').val();
        if (${id}Value != null && ${id}Value != "" && ${id}Value != undefined) {
            ${id}View(${id}Value);
            ${id}bindImgShow();

        }
    });

    function ${id}bindImgShow(){
        $("#${id}file img").bind("click",function () {
            var imgArr = $("#${id}file img");

            var index = "0";
            var thisSrc = $(this).attr("src");

            var imgData = [];
            for (var i=0,len = imgArr.length;i<len;i++){
                var imageSrc = imgArr[i].getAttribute("src");
                var indexOf = imageSrc.lastIndexOf("/");
                var imageName = imageSrc.substring(indexOf+1,imageSrc.length);
                var data = {
                    "alt": imageName,
                    "pid": i, //图片id
                    "src": imageSrc, //原图地址
                    "thumb": "" //缩略图地址
                };
                if (thisSrc == imageSrc){   // 根据当前src 获得索引, 设置相册起始值
                    index = i;
                }
                imgData.push(data);
            }


            var imageJson = {
                "title": "证照路径", //相册标题
                "id": 123, //相册id
                "start": index, //初始显示的图片序号，默认0
                "data": imgData
            };

            showImage(imageJson);
        })
    }

     function showImage(imageJson) {
           layer.photos({
                photos: imageJson,
                tab: function(pic, layero){

                }
            });
        }

</script>




